import React, { Fragment, useCallback, useMemo, useState } from "react";
import { Upload, Button, message,Table, Space, Modal } from "antd";
import type { ColumnsType } from 'antd/es/table';
import { connect, mapProps, useField, mapReadPretty } from "@formily/react";
import axios from "axios";
import clsx from "clsx";

// const Uploda = (props:any)=> {
//   console.log(props)
//   return <Button>
//     UploadShowTable
//   </Button>
// }

// export const UploadShowTable = connect(Uploda,
// mapProps({
//   value: 'fileList',
// }),
// mapReadPretty(Uploda, { readPretty: true })
// )

interface DataType {
  id:string
  key: string;
  name: string;
  suffix: number;
  size: number;
  create_time: string;
  path: string;
}


export const UploadShowTable = React.forwardRef((props: any, ref: any) => {
  console.log(props);

  const [loading, setLoading] = useState(false);

  const disabled = useMemo(()=>{
    return props.disabled
  },[props.disabled])

  const readOnly = useMemo(()=>{
    return props.readOnly
  },[props.readOnly])

  const value = useMemo(()=>{
    if(!props.value) return []
    return props.value
  },[props.value])

  const beforeUpload = useCallback((file:File) => {
    setLoading(true);
    if (value.length >= props.maxCount) {
      message.warning('超出上传限制');
      setLoading(false);
      return false;
    }

    if (file.size > props.size * 1024 * 1024) {
      message.warning('文件过大');
      setLoading(false);
      return false;
    }
  },[value, props.maxCount, props.size]);

  const customRequest = (response:any)=>{
    const formData = new FormData();
      formData.append('file', response.file);
      axios.post(props.action, formData,{
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }).then(res=>{
          setLoading(false)
          if (res.data.code == 200) {
            props.onChange([...value, res.data.data]);
          }
      })
  }

  const size = useMemo(()=>{
    if(!props.size) return 0;
    return props.size / 1024
  },[props.size])


  const preview = (record: DataType) => {
    // window.open(
    //   window.config.baseUrl + useStore.route_map.attachment + record.path,
    //   '_blank'
    // );
  };
  const deleteFile = async (record: DataType) => {
    Modal.confirm({
      title: '系统提示',
      content: '确认删除？',
      onOk() {
        props.onChange(value.filter((item:any) => item.id !== record.id));
      },
    })
  };


  const columns:ColumnsType<DataType> = [
    {
      title: "文件名",
      dataIndex: "name",
      key: "name",
      render: (_, { name,suffix }) => <div>{name + '.' + suffix}</div>
    },
    {
      title: "大小",
      dataIndex: "size",
      key: "size",
    },
    {
      title: "上传时间",
      dataIndex: "create_time",
      key: "create_time",
    },
    {
      title: "操作",
      dataIndex: "operation",
      key: "operation",
      render: (_, record) => (
        <Space size="middle">  
          <Button
            type="link"
            onClick={() => preview(record)}
          >
            预览
          </Button>
          <Button
            type="link"
            onClick={()=>deleteFile(record)}
          >
            删除
          </Button>
        </Space>
      )
    }
  ]

  return (
    <Fragment>
      <Upload
        name={props.name}
        accept={props.accept}
        showUploadList={false}
        maxCount={props.maxCount}
        multiple={props.multiple}
        beforeUpload={beforeUpload}
        customRequest={customRequest}
        className={clsx({
          'hidden': readOnly
        })}
      >
        <Button type="primary" loading={loading} disabled={disabled}>
          {props.textContent}
        </Button>
      </Upload>
      <div
        className={
          clsx(`text-sm text-slate-600 my-2`,{
            'hidden': readOnly
          })
        }
      >
        上传{props.accept}格式，文件大小不能超过{size}MB
      </div>
      <Table pagination={false} dataSource={value} columns={columns}>
      </Table>
    </Fragment>
  );
});

UploadShowTable.displayName = "UploadShowTable";
